<template>
  <doc-alert
    title="【库存】库存调拨、库存盘点"
    url="https://doc.iocoder.cn/erp/stock-move-check/"
  />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="盘点单号" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入盘点单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="盘点时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="盘点人" prop="creator">
        <el-select
          v-model="queryParams.creator"
          clearable
          filterable
          placeholder="请选择盘点人"
          class="!w-240px"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions((DICT_TYPE.APPROVE_STATUS))"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:stock-check:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <!-- <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:stock-check:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column min-width="180" label="盘点单号" align="center" prop="no" />
      <el-table-column min-width="180" label="仓库名称" align="center" prop="deptName" />
      <el-table-column
        label="盘点时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="200px"
      />
      <el-table-column label="盘点人" align="center" prop="creatorName" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.APPROVE_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="220">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('detail', scope.row.id)"
            v-hasPermi="['erp:stock-check:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:stock-check:update']"
            v-if="scope.row.status === 2"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            @click="updateStatus(scope.row.id, 1)"
            v-hasPermi="['erp:stock-check:update-status']"
            v-if="scope.row.status === 0"
          >
            提交
          </el-button>
          <!-- <el-button
            link
            type="danger"
            @click="handleDelete([scope.row.id])"
            v-if="scope.row.status !== 1"
            v-hasPermi="['erp:stock-check:delete']"
          >
            删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <StockCheckForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { StockCheckApi, StockCheckVO } from '@/api/spd/hospitaloffice/stockcheck'
import StockCheckForm from './StockCheckForm2.vue'
// import { PriStockApi, PriStockVO } from '@/api/erp/pristock'
import { SecStockApi, SecStockVO } from '@/api/erp/secstock'
// import { ProductApi, ProductVO } from '@/api/erp/product/product'
// import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { UserVO } from '@/api/system/user'
import * as UserApi from '@/api/system/user'
import { number } from 'vue-types'

/** ERP 其它盘点单列表 */
defineOptions({ name: 'ErpStockCheck' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<StockCheckVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

var deptId2: undefined
// var userName: string
onMounted(() => {
  const Info = JSON.parse(localStorage.getItem('user') || '{}');
  const userInfo = JSON.parse(Info.v)
  deptId2 = userInfo.user.deptId
  // userName = userInfo.user.name
});


const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deptId: undefined,
  creator: undefined,
  warehouseLevel: '2',
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const productList = ref<SecStockVO[]>([]) // 产品列表
// const warehouseList = ref<WarehouseVO[]>([]) // 仓库列表
const userList = ref<UserVO[]>([]) // 用户列表

// const customSort = (a: StockCheckVO, b: StockCheckVO) => {
//   const order = [0,3, 2, 1]
//   return order.indexOf(a.status) - order.indexOf(b.status)
// }

const updateStatus = async (id: number, status: number) => {
  try {
    // 更改状态的二次确认
    await message.confirm(`确定提交该盘点单吗？`)
    // 发起更改状态
    await StockCheckApi.updateStockCheckStatus(id, status)
    message.success(t('common.updateSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.warehouseLevel = '2'
    const data = await StockCheckApi.getStockCheckPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (ids: number[]) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await StockCheckApi.deleteStockCheck(ids)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    selectionList.value = selectionList.value.filter((item) => !ids.includes(item.id))
  } catch {}
}

/** 审批/退回操作 */
const handleUpdateStatus = async (id: number, status: number) => {
  try {
    // 审批的二次确认
    await message.confirm(`确定${status === 1 ? '审批' : '退回'}该盘点单吗？`)
    // 发起审批
    await StockCheckApi.updateStockCheckStatus(id, status)
    message.success(`${status === 1 ? '审批' : '退回'}成功`)
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await StockCheckApi.exportStockCheck(queryParams)
    download.excel(data, '其它盘点单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 选中操作 */
const selectionList = ref<StockCheckVO[]>([])
const handleSelectionChange = (rows: StockCheckVO[]) => {
  selectionList.value = rows
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 加载产品、仓库列表、客户
  const data = await SecStockApi.getSecStockList()
  productList.value = data.list
  userList.value = await UserApi.getSimpleUserList()
})


// TODO 芋艿：可优化功能：列表界面，支持导入
// TODO 芋艿：可优化功能：详情界面，支持打印
</script>
